package com.ac.scum.log.web.model.player.service;

import com.ac.common.core.exception.BaseException;
import com.ac.scum.log.bean.Player;
import com.ac.scum.log.bean.PlayerVO;
import com.ac.scum.log.web.model.player.mapper.PlayerMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PlayerService extends ServiceImpl<PlayerMapper, Player> {


    public List<Player> findPlayersByName(Long serverId, String name) throws BaseException {
        String where = "1=1 ";
        try {
            where += " or pjs.player_steam_id = " + Long.parseLong(name);
        } catch (Exception ignored) {
        }
        return this.getBaseMapper().findPlayersByServerIdAndNameLike(serverId, name.replace("'", ""), where);
    }

    public IPage<PlayerVO> findPlayerPage(Long currentServerId, PlayerVO player, Long current, Long size) {
        StringBuilder sql = new StringBuilder("1=1");
        if (player != null) {
            if (StringUtils.isNotBlank(player.getName())) {
                sql.append(" and pjs.name like '%").append(player.getName()).append("%' ");
            }
            if (StringUtils.isNotBlank(player.getSteamName())) {
                sql.append(" and p.steam_name like '%").append(player.getSteamName()).append("%' ");
            }
            if (player.getSteamId() != null) {
                sql.append(" and p.steam_id = ").append(player.getSteamId()).append(" ");
            }
            if (player.getId() != null) {
                sql.append(" and p.id = ").append(player.getId()).append(" ");
            }
            if (StringUtils.isNotBlank(player.getFakeName())) {
                sql.append(" and pjs.fake_name like '%").append(player.getFakeName()).append("%' ");
            }
            if (player.getBalance() != null) {
                sql.append(" and pb.balance >= ").append(player.getBalance()).append(" ");
            }
            if (player.getTotalBalance() != null) {
                sql.append(" and pb.total_balance >= ").append(player.getTotalBalance()).append(" ");
            }
        }
        return this.baseMapper.findPlayerPageByWhereSql(currentServerId, sql.toString(), new Page<>(current, size));
    }

    public Player findPlayerById(Long serverId, Long playerId){
        return this.baseMapper.findPlayerByServerIdAndId(serverId, playerId);
    }
}
